<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-row>
          <span>{{title}}</span>
        </el-row>
        <el-form :model="newForm" :rules="rules" ref="newForm" label-width="100px" class="newForm">
            <el-form-item label="学科" prop="subjectID">
              <el-select v-model="newForm.subjectID" @change="selectSub('change')">
                <el-option  v-for="item in objList" :key="item.id" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>

             <el-form-item label="目录" prop="catalogID">
              <el-select v-model="newForm.catalogID">
                <el-option  v-for="item in currentMenu" :key="item.id" :label="item.directoryName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="企业" prop="enterpriseID">
              <el-select v-model="newForm.enterpriseID">
                <el-option  v-for="item in enterpriseList" :key="item.id" :label="item.company" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="城市" prop="province" ><city :value='newForm'  @input="input"/></el-form-item>

            <el-form-item label="方向" prop="direction">
              <el-select v-model="newForm.direction">
                <el-option  v-for="item in directionList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="题型" prop="questionType">
              <el-radio-group v-model="newForm.questionType" @change="changeQtype">
                <el-radio v-for="(item,index) in questionTypes" :key="index" :label="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="难度" prop="difficulty">
              <el-radio-group v-model="newForm.difficulty">
                <el-radio v-for="(item,index) in difficultys" :key="index" :label="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="题干" prop="question">
              <quill-editor v-model="newForm.question" class="editor"></quill-editor>
            </el-form-item>

            <!--单选 -->
            <el-form-item label="选项" v-if="newForm.questionType===1">
              <el-row  v-for="(item,index) in newForm.options" :key="index" style="margin-bottom:20px" >
                  <el-radio   v-model="radioRight" :label="item.code" >{{item.code}}:
                    <el-input v-model="item.title"></el-input>
                  </el-radio>
              </el-row>
            </el-form-item>

            <!-- 多选-->
             <el-form-item label="选项" v-if="newForm.questionType===2">
                <el-row  v-for="(item,index) in newForm.options" :key="index" style="margin-bottom:20px" >
                    <el-checkbox :label="item.code" v-model="checkBoxRight">
                      {{item.code}}:
                      <el-input v-model="item.title"></el-input>
                    </el-checkbox>
                </el-row>
             </el-form-item>

             <el-form-item v-if="newForm.questionType!==3">
                  <el-button type="danger" size="mini" @click="addCheck" :disabled='newForm.questionType===1'>增加选项与答案</el-button>
             </el-form-item>

            <el-form-item label="解析视频">
              <!-- <el-input v-model="newForm.videoURL"></el-input> -->
                <input ref="img" type="file" accept=".mp4" @change="upload" >
                <div class="imgProgress">
                  <el-progress v-if="showProgress" :percentage="percentage" status="success" />
                </div>
            </el-form-item>

            <el-form-item label="答案解析" prop="answer">
              <quill-editor v-model="newForm.answer" class="editor"></quill-editor>
            </el-form-item>

            <el-form-item label="题目备注">
              <el-input v-model="newForm.remarks"></el-input>
            </el-form-item>

            <el-form-item label="试题标签">
                <el-select v-model="tags" multiple  filterable allow-create  default-first-option placeholder="请选择">
                <el-option
                  v-for="item in tagList"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.id">
                </el-option>
                </el-select>
            </el-form-item>

             <el-form-item>
                <el-button :type="id?'success':'primary'" @click="submitForm" size="mini">{{id?'确认修改':'确认提交'}}</el-button>
              </el-form-item>

        </el-form>
        <!-- <p v-for="(i,index) in newForm" :key="index">{{newForm[index]}}</p> -->

      </el-card>
    </div>
  </div>
</template>

<script>

import { detail, add, update } from '@/api/hmmm/questions.js'
import { simple } from '@/api/hmmm/subjects.js'
import { list as getEtp } from '@/api/hmmm/companys.js'
import { list as direList } from '@/api/hmmm/directorys.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { list as tagList } from '@/api/hmmm/tags.js'
import COS from 'cos-js-sdk-v5'

export default {
  components: {
    city: () => import('./companys/citys.vue')
  },
  data () {
    // 自定义  判断城市是否存在
    const checkCity = (rule, value, callback) => {
      if (value && this.newForm.city === '') {
        return callback(new Error('请选择城市!'))
      } else {
        callback()
      }
    }
    return {
      // 试题id
      id: '',
      // 组件标题
      title: '',
      // 添加或者修改的表单
      newForm: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        province: '',
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: 1,
        // 难度
        difficulty: 1,
        // 题干
        question: '',
        // 选择 可能是单选多选
        options: [
          // 0 为错误答案  1为正确答案
          { questionsID: '', code: 'A', title: '', img: '', isRight: 0 },
          { questionsID: '', code: 'B', title: '', img: '', isRight: 0 },
          { questionsID: '', code: 'C', title: '', img: '', isRight: 0 },
          { questionsID: '', code: 'D', title: '', img: '', isRight: 0 }
        ],
        // 解析视频
        videoURL: '',
        // 答案解析  简答题
        answer: '',
        // 题目备注
        remarks: '',
        tags: ''
      },
      // 表单校验z
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        // 目录
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        // 企业
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        province: [{ required: true, message: '请输入完整城市信息', trigger: 'blur' },
          { validator: checkCity, trigger: 'blur' }
        ],
        // city: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        // 方向
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        // 题型
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        // 难度
        difficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        // 题干
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        // 答案解析
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      },
      // 学科列表
      objList: [],
      // 选中的二级目录
      currentMenu: [],
      // 所所有企业
      enterpriseList: [],
      // 方向列表
      directionList: [],
      // 题型难度数组
      questionTypes: [],
      // 难度
      difficultys: [],
      // 单选确答案  ABCD  回显是遍历
      radioRight: '',
      // 多选框数组
      checkBoxRight: [],
      // 试题标签 数据源
      tagList: [],
      // 试题标签
      tags: [],
      cos: null,
      percentage: 0,
      showProgress: false
    }
  },
  created () {
    this.id = this.$route.query.id
    this.title = this.id ? '试题修改' : '试题录入'
    this.directionList = direction
    this.questionTypes = questionType
    this.difficultys = difficulty

    this.cos = new COS({
      SecretId: 'AKIDkGXYHjtmPlqdARSCgtpUszoMegRu61g4', // 身份识别 ID
      SecretKey: '80cx1nIXVBbkcCVYKq53k9H9k47tOcZG' // 身份密钥
    })
    this.getQuestionById()
    this.getObjList()
    this.getEtpList()
  },
  methods: {
    // 恒聚传出来的id获取试题详情
    async getQuestionById () {
      // 判断id是否存在  比存在结束
      if (!this.id) return
      const { data: res } = await detail({ id: this.id })
      res.questionType = +res.questionType
      res.difficulty = +res.difficulty
      this.newForm = res
      // 获取到书签
      const subjectID = this.newForm.subjectID
      const { data: tags } = await tagList({ subjectID, pagesize: 99999 })
      this.tagList = tags.items

      this.newForm.tags = this.newForm.tags.replace(/,/g, '，')
      console.log(this.newForm.tags)
      // 添加到绑定的数组列表中

      this.tags = this.newForm.tags.split('，')

      // 数据回显按钮部分
      if (this.newForm.questionType === 1) {
        const index = this.newForm.options.findIndex(item => item.isRight === 1)
        this.radioRight = this.newForm.options[index].code
      } else if (this.newForm.questionType === 2) {
        this.newForm.options.forEach(item => {
          if (item.isRight === 1) {
            this.checkBoxRight.push(item.code)
          }
        })
      }

      this.selectSub('load')
    },
    // 初始化学科列表
    async getObjList () {
      const { data: res } = await simple()
      this.objList = res
    },

    // 学科级联二集目录
    async  selectSub (val) {
      // 如果是切换触发 那么清空
      if (val === 'change') {
        this.newForm.catalogID = ''
      }

      this.currentMenu = []
      const { data: res } = await direList({ subjectID: this.newForm.subjectID, pagesize: 99999 })
      this.currentMenu = res.items
      console.log(this.currentMenu)
    },
    // 获取企业;列表
    async getEtpList () {
      const { data: res } = await getEtp({ pagesize: 99999 })
      this.enterpriseList = res.items
    },
    // 地址级联触发事件
    input (val) {
      this.newForm.province = val.province
      this.newForm.city = val.city
    },
    // 点击切换提醒的难度
    changeQtype () {
      // 清除之前选中的
      // 清除之前选中的状态
      this.radioRight = ''
      // 多选框数组
      this.checkBoxRight = []
      this.newForm.options.forEach(item => {
        item.isRight = 0
      })
    },
    addCheck () {
      // code值逐渐增加  通过hash值相互转换
      const code = String.fromCharCode(0x40 + this.newForm.options.length + 1)
      const obj = { questionsID: '', code, title: '', img: '', isRight: 0 }
      this.newForm.options.push(obj)
    },
    // 提交数据
    submitForm () {
      this.$refs.newForm.validate(async valid => {
        if (!valid) return
        // 判断下试题类型
        console.log('请求后台去了')
        if (this.newForm.questionType === 1) {
          if (this.radioRight) {
            const index = this.newForm.options.findIndex((item, index) => item.code === this.radioRight)

            this.newForm.options.forEach(item => {
              item.isRight = 0
            })

            this.newForm.options[index].isRight = 1
          }
        } else if (this.newForm.questionType === 2) {
        // 多选
        // 判断数组不为空
          if (this.checkBoxRight.length !== 0) {
            this.newForm.options.forEach(item => {
              if (this.checkBoxRight.includes(item.code)) {
                item.isRight = 1
              } else {
                item.isRight = 0
              }
            })
          } else {
            this.newForm.options.forEach(item => {
              item.isRight = 0
            })
          }
        }
        this.newForm.tags = this.tags.join('，')
        // 将题型 和难度转换成String类型
        this.newForm.questionType = this.newForm.questionType.toString()
        this.newForm.difficulty = this.newForm.difficulty.toString()

        console.log(this.checkBoxRight)

        // 根据id判断是修改还是添加
        if (this.id) {
          // 修改
          await update(this.newForm)
          this.$message.success('试题修改成功!')
        } else {
          // 调用axios
          await add(this.newForm)
          this.$message.success('试题添加成功!')
        }
        this.$router.push('/questions/list')
      })
    },
    // 视频上传
    upload () {
      this.showProgress = true
      const data = this.$refs.img.files[0]
      console.log(data)
      this.cos.putObject({
        Bucket: 'hrsaas-1308447471', /* 必须 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: data.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: data, // 上传文件对象
        onProgress: (progressData) => {
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (err) {
          this.$message.error('上传失败!')
        } else {
          this.$message.success('上传成功!')
          setTimeout(() => {
            this.showProgress = false
          }, 1000)
          this.newForm.videoURL = 'https://' + data.Location
          // console.log(this.newForm.videoURL)
        }
      })
    }

  }
}
</script>

<style scoped>
.newForm{
  margin-top: 30px;
}
.el-input,.el-select{
  width: 400px;
}
.editor{
  /* height: 200px; */
}
.imgProgress{
  width: 200px;
}

</style>
